var MyID = '';
var loading = true;

//判断是否移动端
var isMobile = window.screen.width < 512;
let title = isMobile ? 'FB Player' : 'FreeBasic Playground';
let isQQ = window.navigator.userAgent.includes('MQQBrowser');
let isWX = window.navigator.userAgent.includes('MicroMessenger');
document.querySelector('.title .big').innerText = title;
if (isMobile) {
    document.querySelector('.title .small').innerText = '';
    if (!isQQ && !isWX) {
        //适配普通手机浏览器
        $('#foot').hide();
        $('#btnF9').show();
        $('#result').css('bottom', '0px');
    }
}

var tid = setInterval(function () {
    if (editor) {
        clearInterval(tid);
        loading = false;
        layer.msg('hello freebasic');
    }
}, 100);


// 初始化编辑器
var editor = monaco.editor.create(document.getElementById('container'), {
    // value: ['function x() {', '\tconsole.log("Hello world!");', '}'].join('\n'),
    // language: 'javascript'
    // value: ['function x()', '\tprint "Hello world!"', 'end function'].join('\n'),
    language: 'vb'
});


editor.onDidChangeModelContent((event) => {
    // event.changes 包含了所有改变的详细信息
    // console.log('编辑器事件', event);
    // console.log('编辑器内容发生变化', event.changes);
    // // event.eol 表示新的行尾符
    // console.log('新的行尾符', event.eol);
    // // event.versionId 表示模型的新版本ID
    // console.log('模型的新版本ID', event.versionId);
    // // event.isUndoing 表示是否是撤销操作
    // console.log('是否是撤销操作', event.isUndoing);
    // // event.isRedoing 表示是否是重做操作
    // console.log('是否是重做操作', event.isRedoing);

    saveContent();
});

function guid() {
    // 生成 UUID
    var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = (Math.random() * 16) | 0;
        var v = c === 'x' ? r : (r & 0x3) | 0x8;
        return v.toString(16);
    });
    return uuid;
}

function saveContent() {
    var content = editor.getValue();
    localStorage.setItem('content', content);
}
function saveParams() {
    var content = $('#parameters').val();
    localStorage.setItem('params', content);
}

function restoreContent() {
    var content = localStorage.getItem('content');
    if (content) {
        editor.setValue(content);
    } else {
        editor.setValue(defaultContent());
    }
}

function defaultContent() {
    return `' 这是一个 FreeBasic 语言的练习场
' 你可以运行任何不含UI的示例，比如官方包里面的
' 包括文件读写，多线程，数据库等操作
' 并且包含了官方 include 目录
' 可以粘贴代码进来，所有代码变化会本地缓存
' 随时按 F2 可以运行代码，F9 显示或隐藏结果
' 编辑快捷键和 vscode 一致，比如注释用 ctrl+/
' 有任何问题请联系：woeoio@qq.com

' This is a practice area for the FreeBasic language.
' You can run any UI-free samples, EXP: the official package.
' It includes operations such as file I/O, multithreading, and databases.
' And it includes the official [ include ] directories.
' You can paste code here, and all code changes will be locally cached.
' Press F2 at any time to run the code, and F9 to show or hide the results.
' The editing shortcuts are consistent with Visual Studio Code, try Ctrl+/.
' If you have any questions, please contact: woeoio@qq.com

#include once "fbthread.bi"

sub mythread( byval p as any ptr )
	print "hey! woeoio"
    print "------------------------------------------------"
end sub

threaddetach( threadcreate( @mythread ) )
sleep 1

dim as long i,a
dim s as string
for i = 1 to 200
    a += i
    s += " + " & i
next
print s & " = " & a`;
}
function restoreParams() {
    var content = localStorage.getItem('params');
    // if (content) {
    $('#parameters').val(content)
    // }
}
function setMyID() {
    var myid = localStorage.getItem('myid');
    if (!myid) {
        // 生成GUID
        myid = guid();
        localStorage.setItem('myid', myid);
    }
    MyID = myid;
}

function init() {
    setMyID();
    restoreContent();
    restoreParams();
}
init()

function toggleResult(open) {
    var result = document.getElementById('result');
    if (result.style.display === 'none' || open) {
        result.style.display = 'block';
    } else {
        result.style.display = 'none';
    }
}

var isBusy = false;
function runCode() {
    var code = editor.getValue();
    var params = $('#parameters').val();
    if (!code) {
        layer.alert('code is empty', {
            icon: 2,
            title: 'error',
            btn: ['ok']
        });
        return;
    }
    layer.msg('running...in 60s', { time: 0, shade: 0.5 });
    isBusy = true;
    $.ajax({
        url: '/run',
        type: 'POST',
        data: {
            myid: MyID,
            code: code,
            params: params
        },
        success: function (data) {
            // console.log(data);
            $('#result pre').text(data);
        },
        error: function (xhr, status, error) {
            $('#result pre').text(error + '\n' + xhr.responseText);
        },
        complete: function () {
            isBusy = false;
            toggleResult(1);
            layer.msg('finish');
        }
    })
}
document.addEventListener('keydown', function (event) {
    // 检查是否按下了 F5 键
    // if (event.keyCode === 116 || event.code === 'F5') {
    //     // 阻止默认的刷新行为
    //     event.preventDefault();
    //     // 可以在这里执行你想要的操作
    //     console.log('F5 key pressed, but refresh is prevented.');
    // }
    if (event.code === 'F2') {
        // console.log('F2 key pressed');
        if (isBusy) return
        runCode();
        // 执行你想要的操作
    }
    if (event.code === 'F9') {
        // console.log('F9 key pressed');
        // 执行你想要的操作
        toggleResult();
    }
    // if (event.code === 'Escape') {
    //     console.log('Escape key pressed');
    //     // 执行你想要的操作
    // }
});

// $('#result pre').text(window.navigator.userAgent)

function aboutMe() {
    layer.open({
        type: 2,
        title: 'About Me',
        // skin: 'layui-layer-rim', //加上边框
        area: ['350px', '500px'], //宽高
        content: 'about.html'
    })
}